package com.jiangyao.interceptor;


import com.jiangyao.common.constants.CacheConstants;
import com.jiangyao.common.constants.ConfigConstants;
import com.jiangyao.common.constants.SystemConstants;
import com.jiangyao.common.exception.ServerException;
import com.jiangyao.common.utils.SpringBeanFactoryUtils;
import com.jiangyao.common.utils.StringUtils;
import com.jiangyao.component.RedisComponent;
import com.jiangyao.model.dto.backend.AdminUserDTO;
import com.jiangyao.model.vo.AdminUserSessionVO;
import com.jiangyao.service.AdminUserService;
import com.jiangyao.service.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @author: yangyongchuan
 * @create: 2020年04月17日 10:23
 */
public class LoginInterceptor implements HandlerInterceptor {

	private static final Logger LOGGER = LoggerFactory.getLogger(LoginInterceptor.class);

	private static ConfigService configService;

	private static AdminUserService adminUserService;

	private static RedisComponent redisComponent;

	static {
		if (configService == null) {
			configService = SpringBeanFactoryUtils.getBean(ConfigService.class);
		}
		if (redisComponent == null) {
			redisComponent = SpringBeanFactoryUtils.getBean(RedisComponent.class);
		}
		if (adminUserService == null) {
			adminUserService = SpringBeanFactoryUtils.getBean(AdminUserService.class);
		}
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 从session 获取登录用户
		AdminUserSessionVO adminUserSessionVO = null;

		// 获取token
		String token = request.getHeader(SystemConstants.LOGIN_TOKEN);
		if (StringUtils.isBlank(token)) {
			token = request.getParameter(SystemConstants.LOGIN_TOKEN);
		}
		if (StringUtils.isNotBlank(token)) {
			adminUserSessionVO = redisComponent.getObject(CacheConstants.CACHE_KEY_TOKEN_BACKEND_PREFIX + token);
		}
		if (adminUserSessionVO == null || adminUserSessionVO.getAdminId() == null) {
			adminUserSessionVO = autoLogin(adminUserSessionVO);
		}

		if (adminUserSessionVO == null || adminUserSessionVO.getAdminId() == null) {
			throw new ServerException(403, "用户未登录");
		}
		adminUserSessionVO = adminUserService.packageOrgAndClass(adminUserSessionVO);
		// 将登录用户信息放入request
		request.setAttribute("_userSession", adminUserSessionVO);
		request.setAttribute("_uid", adminUserSessionVO.getAdminId());
		request.setAttribute("_username", adminUserSessionVO.getAdminName());
		request.setAttribute("_token", token);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}


	/**
	 * 模拟自动登录（admin账号）
	 * adminUserSessionVO为空时，根据配置 "backend.auto.login",自动使用admin账号登录
	 *
	 * @param adminUserSessionVO 登录信息
	 * @return 登录信息
	 */
	private AdminUserSessionVO autoLogin(AdminUserSessionVO adminUserSessionVO) {
		if (adminUserSessionVO != null) {
			return adminUserSessionVO;
		}
		// 模拟登录
		String BACKEND_AUTO_LOGIN = configService.getValueFromCache(ConfigConstants.BACKEND_AUTO_LOGIN);
		if (!"true".equals(BACKEND_AUTO_LOGIN)) {
			return adminUserSessionVO;
		}

		AdminUserService adminUserService = SpringBeanFactoryUtils.getBean(AdminUserService.class);
		AdminUserDTO adminUserDTO = new AdminUserDTO();
		adminUserDTO.setLoginName("admin");
		adminUserDTO.setPassword("123456");
		adminUserSessionVO = adminUserService.login(adminUserDTO);

		return adminUserSessionVO;
	}
}
